package com.valuegroup.smarttodo.ui.todo.habit;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.model.AppStatus;
import com.valuegroup.smarttodo.data.model.Habit;
import com.valuegroup.smarttodo.ui.BaseActivity;
import com.valuegroup.smarttodo.plugins.ClickableTextView;
import com.valuegroup.smarttodo.plugins.MultilineEditText;
import com.valuegroup.smarttodo.plugins.pickdialog.DatePickDialog;
import com.valuegroup.smarttodo.plugins.pickdialog.OnCustomSureLisener;
import com.valuegroup.smarttodo.plugins.pickdialog.bean.DateType;
import com.valuegroup.smarttodo.util.AlertUtils;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.PopupMenu;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 习惯表单
 * 用于习惯新增修改
 */
public class HabitActivity extends BaseActivity {

    @BindView(R.id.labTitle)
    ClickableTextView labTitle;
    @BindView(R.id.labTitleEdit)
    MultilineEditText labTitleEdit;
    @BindView(R.id.labDesc)
    ClickableTextView labDesc;
    @BindView(R.id.labDescEdit)
    MultilineEditText labDescEdit;
    @BindView(R.id.tagEmoji)
    ImageView tagEmoji;
    @BindView(R.id.labMinute)
    TextView labMinute;
    @BindView(R.id.btnChoicePreMinute)
    LinearLayout btnChoicePreMinute;
    @BindView(R.id.labHeaderTitle)
    TextView labHeaderTitle;
    @BindView(R.id.rootLayout)
    LinearLayout rootLayout;
    @BindView(R.id.layoutTitle)
    FrameLayout layoutTitle;
    @BindView(R.id.layoutSubtitle)
    FrameLayout layoutSubtitle;

    @BindView(R.id.btnQuadrant)
    LinearLayout btnQuadrant;
    @BindView(R.id.labQuadrant)
    TextView labQuadrant;
    @BindView(R.id.imgQuadrant)
    ImageView imgQuadrant;

    private PopupMenu menuQuadrant;
    private Long DATA_ID;
    private Integer DATA_POSITION;
    private Habit DATA;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_habit);
        ButterKnife.bind(this);

        initView();
        initData();
    }

    private void initData() {

        DATA_ID = getIntent().getLongExtra(PARAMS_KEY, 0);
        DATA_POSITION = getIntent().getIntExtra(PARAMS_POSITION, 0);
        DATA = ServiceFactory.getInstance().getHabitService().getHabitDao().load(DATA_ID);

        if (DATA_ID != 0 && DATA == null) {
            AlertUtils.showToast(getApplicationContext(), R.string.not_found_record);
            finish();
            return;
        }

        if (DATA_ID == 0) {
            DATA = ServiceFactory.getInstance().getHabitService().getDefaultHabit();
            DATA.setPreMinute(10);
        }

        labTitle.setText(DATA.getTitle());
        labDesc.setText(DATA.getDesc());
        labMinute.setText(String.format(getResources().getString(R.string.lab_minute), DATA.getPreMinute()));

        // 优先级
        labQuadrant.setText(AppStatus.QuadrantLabArr[DATA.getQuadrant()]);
        imgQuadrant.setImageResource(AppStatus.QuadrantTagArr[DATA.getQuadrant()]);
    }

    private void initView() {
        // 习惯标题编辑状态控制
        labTitleEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    labTitleEdit.setVisibility(View.GONE);
                    labTitle.setText(v.getText());
                    labTitle.setVisibility(View.VISIBLE);
                }
                // 返回true，保留软键盘。false，隐藏软键盘
                return true;
            }
        });


        labTitleEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    // 得到焦点

                    // 光标移动到末尾
                    labTitleEdit.setSelection(labTitleEdit.getText().length());

                    // 弹出键盘
                    InputMethodManager inputManager = (InputMethodManager) labTitleEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputManager.showSoftInput(labTitleEdit, 0);
                } else {
                    // 失去焦点
                    labTitleEdit.setVisibility(View.GONE);
                    labTitle.setText(labTitleEdit.getText());
                    labTitle.setVisibility(View.VISIBLE);
                }
            }
        });


        // 习惯描述编辑状态控制
        labDescEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    labDescEdit.setVisibility(View.GONE);
                    labDesc.setText(v.getText());
                    labDesc.setVisibility(View.VISIBLE);
                }
                // 返回true，保留软键盘。false，隐藏软键盘
                return true;
            }
        });


        labDescEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    // 得到焦点

                    // 光标移动到末尾
                    labDescEdit.setSelection(labDescEdit.getText().length());

                    // 弹出键盘
                    InputMethodManager inputManager = (InputMethodManager) labDescEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputManager.showSoftInput(labDescEdit, 0);
                } else {
                    // 失去焦点
                    labDescEdit.setVisibility(View.GONE);
                    labDesc.setText(labDescEdit.getText());
                    labDesc.setVisibility(View.VISIBLE);
                }
            }
        });


        // 优先级
        menuQuadrant = new PopupMenu(this, labQuadrant);
        menuQuadrant.inflate(R.menu.menu_quadrant);
        menuQuadrant.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.m1:
                        DATA.setQuadrant(AppStatus.Quadrant.ONE);
                        break;
                    case R.id.m2:
                        DATA.setQuadrant(AppStatus.Quadrant.TWO);
                        break;
                    case R.id.m3:
                        DATA.setQuadrant(AppStatus.Quadrant.THREE);
                        break;
                    case R.id.m4:
                        DATA.setQuadrant(AppStatus.Quadrant.FOUR);
                        break;
                }
                labQuadrant.setText(item.getTitle());
                imgQuadrant.setImageResource(AppStatus.QuadrantTagArr[DATA.getQuadrant()]);
                return false;
            }
        });
    }

    @OnClick({R.id.btnBack, R.id.btnSave, R.id.tagEmoji, R.id.btnChoicePreMinute, R.id.labTitle, R.id.labDesc, R.id.btnQuadrant})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnBack:
                setCloseParams();
                finishAfterTransition();
                break;
            case R.id.btnSave:
                if (labTitle.getText().length() == 0 || labDesc.getText().length() == 0) {
                    AlertUtils.showToast(getApplicationContext(), R.string.not_inset_content);
                    return;
                }
                if (DATA.getId() == null && ServiceFactory.getInstance().getHabitService().existHabitName(labTitle.getText().toString())) {
                    AlertUtils.showToast(getApplicationContext(), R.string.exist_content);
                    return;
                }

                DATA.setTitle(labTitle.getText().toString());
                DATA.setDesc(labDesc.getText().toString());
                ServiceFactory.getInstance().getHabitService().saveHabit(DATA);
                if (DATA_ID != 0) {
                    setCloseParams();
                }
                finishAfterTransition();
                break;
            case R.id.tagEmoji:
                break;
            case R.id.btnChoicePreMinute:
                DatePickDialog dialog = new DatePickDialog(this);
                dialog.setType(DateType.TYPE_CUSTOM_MINUTE_INTERVAL_5);
                dialog.setStartData(DATA.getPreMinute());
                dialog.setOnCustomSureLisener(new OnCustomSureLisener() {
                    @Override
                    public void onSure(Object obj) {
                        DATA.setPreMinute((int) obj);
                        String minute = String.format(getResources().getString(R.string.lab_minute), DATA.getPreMinute());
                        labMinute.setText(minute);
                    }
                });
                dialog.show();
                break;
            case R.id.labTitle:
                labTitle.setVisibility(View.GONE);

                labTitleEdit.setText(labTitle.getText());
                labTitleEdit.setVisibility(View.VISIBLE);

                // 获得焦点
                labTitleEdit.setFocusable(true);
                labTitleEdit.setFocusableInTouchMode(true);
                labTitleEdit.requestFocus();
                break;
            case R.id.labDesc:
                labDesc.setVisibility(View.GONE);

                labDescEdit.setText(labDesc.getText());
                labDescEdit.setVisibility(View.VISIBLE);

                // 获得焦点
                labDescEdit.setFocusable(true);
                labDescEdit.setFocusableInTouchMode(true);
                labDescEdit.requestFocus();
                break;
            case R.id.btnQuadrant:
                menuQuadrant.show();
                break;
        }
    }


    @Override
    public void onBackPressed() {
        setCloseParams();
        super.onBackPressed();
    }

    private void setCloseParams() {
        Intent intent = new Intent();
        intent.putExtra(PARAMS_POSITION, DATA_POSITION);
        intent.putExtra(PARAMS_KEY, DATA_ID);
        setResult(RESULT_OK, intent);
    }

}
